/*
 * @Descripttion: 用户管理模块
 * @version: 
 * @Author: WenQingwu
 * @Date: 2022-01-14 15:20:14
 * @LastEditors: WenQingwu
 * @LastEditTime: 2022-03-30 11:34:50
 */

const express = require("express");
const router = express.Router();
const db = require('./../db/config')
const msgJson = require('./msgJson')
// 上传
const upload = require("./../db/uploadconfig");
const { requestSuccess, requestFail } = require("./msgJson");
module.exports = router;

/**
 * 1. 登录接口
 * @param  {String} uaccessno, 用户账号，required.
 * @param  {String} upwd, 用户密码 ，required.
 * @returns {Object} 除密码以外的用户信息。
 */
router.route("/login")
  .post((req, res) => {
    // 判断参数有效性
    let checkResult = msgJson.checkParam(req.body, ['uaccessno', 'upwd']);
    if (checkResult) {
      res.json(checkResult);
      return;
    }
    // 参数有效后才执行后面的代码.
    const { uaccessno, upwd } = req.body;

    let sql = `select * from systemusers where uaccessno = ? and upwd = ?;`;
    let param = [uaccessno, upwd];
    let cb = (err, data) => {
      if (!err && data.length === 1) {
        const userInfo = data[0];
        // 返回一个没有密码的对象。
        delete userInfo.upwd;
        res.json(msgJson.requestSuccess('登录', userInfo))
      } else if (!err && data.length === 0) {
        res.json(msgJson.requestFail('登录', '账号/密码不对!'))
      } else {
        res.json(msgJson.requestFail('登录', '系统错误!'))
      }
    }
    db.connect(sql, param, cb);
  });

/**
 * 2. 创建新用户
 * @param {String} uacessno,账号，最大30个字符，required
 * @param {String} usex,性别，值： 男、女，required
 * @param {String} upwd,密码 6 位，required
 * @param {String} utel,手机号码 11位，required
 * @param {String} usid,身份证 18位，required
 * @param {String} uname,用户姓名 <20位，required
 * @param {Object} uphoto,头像文件，required
 
 */
router.route("/addUser")
  .post(upload.single('uphoto'), (req, res) => {
    // console.log("表单中的其它参数", req.body);
    // console.log("文件名：", req.file);

    // 判断表单其它参数有没有传递
    let checkResult = msgJson.checkParam(req.body, ['uacessno', 'usex', 'upwd', 'utel', 'usid', 'uname']);

    if (checkResult) {
      res.json(checkResult)
      return;
    }
    // 判断有没有上传文件
    checkResult = req.file;
    if (checkResult === undefined) {
      res.json(msgJson.paramIsNull('uphoto'))
      return;
    }
    // 图片存储的文件名
    let uphoto = 'uploads/' + req.file.filename;
    const { uacessno, usex, upwd, utel, usid, uname } = req.body;

    let sql = 'insert into systemusers values(null,?,?,?,?,?,?,?,default)';
    let param = [uacessno, usex, upwd, utel, usid, uphoto, uname]
    let cb = (err, data) => {
      if (!err) {
        res.json(msgJson.requestSuccess('添加新用户'))
      } else {
        console.log(err)
        res.json(msgJson.requestFail('添加新用户', err.sqlMessage))
      }
    }
    db.connect(sql, param, cb)
  });


/**
 * 3. 查询所有用户,模糊查询用户。前端需要自己分页，也可以自己搜索本地数据。
 * @param {String}, searchText 
 * @reutrn {Array} 查询到的数据
 */

router.route('/getUsers')
  .get((req, res) => {
    const { searchText } = req.query;

    searchText !== undefined && typeof searchText === 'string' && (searchText = searchText.trim());

    let sql = 'select uid,uaccessno,usex,utel,usid,uphoto,uname from  systemusers';
    let param = [];

    if (searchText === undefined || searchText.trim().length === 0) {
      sql += ';'
    } else {
      sql += ' where uaccessno like ? or uname like ?;';
      param = ['%' + searchText + '%', '%' + searchText + '%'];
    }

    const cb = (err, data) => {
      if (!err) {
        res.json(msgJson.requestSuccess('查询用户数据', data))
      } else {
        res.json(msgJson.requestFail('查询用户数据', err.sqlMessage))
      }
    }

    db.connect(sql, param, cb)

  })

/**
 * 4. 删除用户
 * @param {string}, uid,用户ID， required.
 */
router.route('/delUser')
  .post((req, res) => {
    console.log(req.body)
    let checkResult = msgJson.checkParam(req.body, ['uid']);
    if (checkResult) {
      res.json(checkResult);
      return;
    }

    let { uid } = req.body;
    // number类型判断
    if (typeof uid !== "number") {
      uid = Number(uid);
      if (isNaN(uid)) {
        msgJson.paramOfType('uid', '参数值不能转换成number类型.');
        return;
      }
    }

    let sql = 'delete from systemusers where uid = ?;'
    let param = [uid];
    const cb = (err, data) => {
      // console.log(data)
      if (!err) {
        res.json(requestSuccess('删除用户'))
      } else {
        res.json(requestFail('删除用户', err.sqlMessage))
      }
    }
    db.connect(sql, param, cb)
  });


/**
 * 5. 修改用户状态
 * @param {String} uid,用户ID，账号，最大30个字符，required. 如：‘111’
 * @param {String} ustate,用户状态，账号，最大30个字符，required. 1 启用，2，禁用
 * @param {String} uacessno,账号，最大30个字符，required
 * @param {String} usex,性别，值： 男、女，required
 * @param {String} upwd,密码 6 位，required
 * @param {String} utel,手机号码 11位，required
 * @param {String} usid,身份证 18位，required
 * @param {String} uname,用户姓名 <20位，required
 * @param {Object} uphoto,头像文件，required
 */
router.route('/modifyUser')
  .post(upload.single('uphoto'), (req, res) => {
    const { uid, uaccessno, usex, upwd, utel, usid, uname, ustate, uphoto } = req.body;
    // 判断表单其它参数有没有传递
    let checkResult = msgJson.checkParam(req.body, ['uid', 'uaccessno', 'usex', 'upwd', 'utel', 'usid', 'uname', 'ustate']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }

    // 判断有没有上传文件

    if (req.file === undefined) {
      // 表示没有修改头像，req.file就不是一个对象，
      checkResult = msgJson.checkParam(req.body, ['uphoto']);
      if (checkResult) {
        res.json(checkResult)
        return;
      }
    } else {
      // 图片存储的文件名
      uphoto = 'uploads/' + req.file.filename;
    }

    let sql = 'update systemusers set uaccessno = ? and usex = ? and upwd = ? and utel = ? and usid = ? and uname = ? and ustate = ? and uphoto = ? where uid = ?;'
    let param = [uaccessno, usex, upwd, utel, usid, uname, ustate, uphoto, uid];
    const cb = (err, data) => {
      if (!err) {
        res.json(requestSuccess('修改用户信息'))
      } else {
        res.json(requestFail('修改用户信息', err.sqlMessage))
      }
    }
  })